# a = 'python'
# b = "python"
# c = """python"""
# print(a, b, c)
#
# print(a[-1])

# test = '   python is a good language!   '
# print(test)
# # 去除首尾空格
# print(test.strip())
# # 去除左边的空格
# print(test.lstrip())
# # 去除右边的空格
# print(test.rstrip())
# print(test.replace('python', '易语言').replace('language', '语言'))
# print(test.split(' '))
# print(test.split(' ')[3])
# print(test.upper())
# print(test.lower())
# print(test.find('is'))
# print(test[test.find('is'):]) # 返回 'is' 出现的后面所有的位置

# 列表
# l = ['python', 1, 2, 3, []]
# print(l)
# l = 'python is a good language! a'.split(' ')
# print(l)
#
# def t(x):
#     return x[0]
# l.sort(key=t)
# print(l)

# l.reverse()
# print(l)

# for i in range(0, l.count('a')):
#     l.remove('a')
# print(l)

# l.remove('a')
# print(l)

# print(l.pop())
# print(l)

# l.append(1)
# print(l)
#
# l.extend([1, 2, 3, 4, 5])
# print(l)
#
# print(l.index('a'))
#
# l.insert(2, 'b')
# print(l)

# a = ('hello', 1, 2, 3, True)
# print(a)

# a = {'Python':1, 'e':2}
# print(a)
#
# a.update({'Python':9, 'go':3})
# print(a)

# for i in a.keys():
#     print(i)

# for i in a.values():
#     print(i)

# print(a.items())
# for i in a.items():
#     print(i)

# print(a.get('go'))
# print(a.get('e'))

# a.clear()
# print(a)

# 登录
# store={'super':123456}
#
# while True:
#     user = input("请输入用户名：")
#     pwd = int(input("请输入密码："))
#     if store.get(user) != None:
#         if pwd == store.get(user):
#             print('登录成功!')
#             break
#         else:
#             print("密码错误！")
#             continue
#     else:
#         print('用户未注册！')
#         continue

# def login(user, pwd):
#         store = {'super': 123456}
#         # user = input("请输入用户名：")
#         # pwd = int(input("请输入密码："))
#         if store.get(user) != None:
#             if pwd == store.get(user):
#                 print('登录成功!')
#                 return True
#             else:
#                 print("密码错误！")
#                 return False
#         else:
#             print('用户未注册！')
#             return False
#
# while True:
#     user = input("请输入用户名：")
#     pwd = int(input("请输入密码："))
#     if login(user, pwd):
#         break
#     else:
#         continue

# class Python:
#     # 公有变量
#     a = 1
#     #私有变量
#     __a = 2
#
#     # 公有方法，内部可以调用私有方法，可以使用私有属性
#     def test1(self):
#         print(f'内部调用：{self.__a}')
#         self.__test2()
#
#     # 私有方法
#     def __test2(self):
#         print('这是私有方法')
#         return
#
# p = Python()
# print(p.a)
# # print(p.__a) # 报错
# p.test1()


# 1.enumerate 循环的时候自带计数（从0开始）
# 2.zip 循环的时候合并多个列表
# names = ['beijing', 'tianjing', 'shanghai', 'chengdu']
# for i, city in enumerate(names):
#     print(i+1, city)

# names = ['beijing', 'tianjing', 'shanghai', 'chengdu']
# ages = [10, 20, 30, 40]
# for age, name in zip(names, ages):
#     print(age, name)

# 1. open
# 2. with
# w 只写
# r 只读
# a 只写追加
# +可读可写

# 第一种方式
# file = open('test.txt', 'a', encoding='utf8')
# file.write('\n这是一个测试') # \n表示换行
# file.close()

# file = open('test.txt', 'a+', encoding='utf8')
# # content = file.read()
# # print(content)
#
# # 一行一行地读
# for i, line in enumerate(file.readlines()):
#     print(i+1, line.strip()) # strip()去除前后的空格
#
# file.close()

# with自开合，as 起别名
# with open('test.txt', 'r', encoding='utf8') as f:
#     file = f.readlines()
#     for fi in file:
#         print(fi.strip())

# class A:
#     def __enter__(self):
#         print('进入了enter')
#         return self
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print(exc_type, exc_val, exc_tb)
#         print('进入了exit')
#         self.file.close()
#
#     def file_op(self):
#         self.file = open('test.txt', 'w', encoding='utf8')
#         self.file.write('写入完成')
# with A() as a:
#     print('进入了with内部作用域')
#     a.file_op()

# def foo(one, *args, **kwargs):
#     print(one)
#     print(args)
#     print(*args)
#     print(kwargs)
#     print(*kwargs)
#
# foo(1, 2, 3, 4, 5, {'aa':6}, kk=7, ll=8)

# 闭包
# 1.外函数--内函数
# 2.外函数返回内函数
# 3.内函数引用了外函数的变量

# def foo():
#     outer=10
#     def inner():
#         nonlocal outer # 在闭包的情况下修改外函数的参数
#         outer=9 # 不是重新声明了一个变量
#         print('inner:', outer)
#         return
#     return inner
#
# res = foo()
# res()

# 装饰器
# 计时装饰器，计算一个函数运行了多长时间

# import time
# def Timer(func):
#     start = time.time()  # 时间戳
#     def warp(*args, **kwargs):
#         # start=time.time() # 时间戳
#         func(*args, **kwargs)
#         end = time.time()
#         print('消耗的时间：', end-start)
#         return
#     return warp
#
# @Timer
# def foo():
#     for i in range(10000000):
#         pass
#
# foo()

# try:
#     a = 1
#     print(b)
# except Exception as e:
#     print('捕获了错误：', e)
# finally:
#     print('finally中的代码一定会执行')
#
# print(a)

# 自定义异常
# 继承异常类 BaseException
# class MyException(BaseException):
#     def __init__(self):
#         print('__init__相当于构造函数')
#
#     # 当这个对象被像字符串输出的话，会执行__str__
#     def __str__(self):
#         return "这是我自定义的类"
#
# # raise 主动发出错误
# raise MyException

# 关于异常处理的包
# import traceback
#
# try:
#     a
# except Exception as e:
#     print(e)
#     traceback.print_exc(file=open('error.txt', 'a+', encoding='utf8'))

# 迭代器可以理解为for循环，循环就是迭代
# 一个迭代器一定要实现下面两个方法
# __next__ 返回下一个方法
# __iter__ 返回迭代器本身

# class MyIter:
#     def __init__(self, num):
#         self.num = num
#
#     def __next__(self):
#         if self.num <= 0:
#             # 一旦超出范围，就 raise 主动捕获
#             raise StopIteration
#         self.num -= 1
#         return self.num
#
#     def __iter__(self):
#         return self
#
# for i in MyIter(10):
#     print(i)

# def crawl():
#     url = 0
#     for i in range(100): # 假设有100个url
#         res = yield url
#         print('接收到了：', res)
#         print('生成了一个url:', url)
#         url+=1
#
# res=crawl()
# print(res)
# next(res) # 重新启动
#
# print(res.send(9999))
# print(res.send(8888))

# 字典不允许重复的值存入
# 数值方法
# 序列方法
# 映射方法
# class DistinctError(BaseException):
#     def __str__(self):
#         return """当传入重复值的时候，引发这个错误"""
#
# class MyDict(dict):
#     def __setitem__(self, key, value):
#         # 看用户传进来的value是否存在value库中，如果存在，就报错
#         if value in self.values():
#             if key not in self:
#                 raise DistinctError
#         super(MyDict, self).__setitem__(key, value)
#
# d = MyDict()
# d['one']='python'
# d['two']='python3'
# print(d)

# a = {'Pyhon':1, 'e':2}
# print(a)
# print(a.get('go'))
# for i in a.values():
#     print(i)
# a.update({'Python':9, 'Go':5})
# a['C++'] = 100
# print(a)

# 直接用[] 要求不会报错，而是返回我们自定义的内容
class MyDict(dict):
    def __init__(self, default):
        self.default = default
        super(MyDict, self).__init__()

    def __getitem__(self, item):
        if item not in self.keys():
            return self.default

        return super(MyDict, self).__getitem__(item)

d = MyDict('no')
d['one'] = 'Python'
d['two'] = 'go'
print(d)


